package userrouter

import (
	"github.com/gin-gonic/gin"
	"nodeseller/crypto"
	"nodeseller/datamodels"
	"nodeseller/encrypt"
	"nodeseller/repositories"
	"nodeseller/response"
)
type UserInfo struct {
	Phonenumber string `json:"phonenumber"`
	Password string `json:"password"`
}
//用户注册
func UserRegister(c *gin.Context)  {
	phone := c.PostForm("phonenumber")
	password := c.PostForm("password")
	if phone == "" || password == ""{
		response.Response1(c, 1,"账号或密码丢失","")
		return
	}
	var userdata datamodels.User
	userdata.PhoneNumber = phone
	userdata.PassWord = password
	//加密密码
	userdata.PassWord = crypto.Md5str(password)
	user := repositories.NewUser()
	if user == nil{
		response.Response1(c,1,"数据错误，请稍后重试","")
		return
	}
	err := user.Insert(&userdata)
	if err != nil{
		response.Response1(c,1,"注册失败，请稍后重试","")
		return
	}
	response.Response1(c,0,"注册成功","")
}
//用户登陆
func UserLogin(c *gin.Context)  {
	//var userinfo datamodels.User
	//buf := make([]byte,1024)
	//n, err := c.Request.Body.Read(buf)
	//err = json.Unmarshal(buf[:n],&userinfo)
	phone := c.PostForm("phonenumber")
	password := c.PostForm("password")
	if phone == "" || password == ""{
		response.Response1(c, 1,"账号或密码丢失","")
		return
	}
	password = crypto.Md5str(password)
	user := repositories.NewUser()
	if user == nil{
		response.Response1(c,1,"数据错误，请稍后重试","")
		return
	}
	err := user.Login(phone,password)
	if err != nil{
		response.Response1(c,1,"登陆失败，请稍后重试","")
		return
	}
	c.SetCookie("phone",phone,0,"/","",false,true)
	phone,err = encrypt.EnPwdCode([]byte(phone))
	if err != nil{
		response.Response1(c,1,"请稍后重试","")
		return
	}
	c.SetCookie("sign",phone,0,"/","",false,true)
	response.Response1(c,0,"登陆成功","")
}
//查询用户信息
func UserGetInfo(c *gin.Context)  {
	phone ,err := c.Cookie("phone")
	if err != nil{
		response.Response1(c,1,"身份验证失败，请重新登陆","")
		return
	}
	user := repositories.NewUser()
	data,err :=user.SelectByKey(phone)
	if err != nil{
		response.Response1(c,1,"数据错误，请稍后重试","")
		return
	}
	response.Response1(c,0,"查询成功",data)
}
